package com.wanpinghui.wphlibrary.model.message;

import android.util.Log;

import com.wanpinghui.wphlibrary.common.IWPHApi;
import com.wanpinghui.wphlibrary.model.base.bean.ImageBean;
import com.wanpinghui.wphlibrary.model.db.manager.MsgDbManager;
import com.wanpinghui.wphlibrary.model.message.bean.GetMsgHistoryResult;
import com.wanpinghui.wphlibrary.model.message.bean.MsgBean;
import com.wanpinghui.wphlibrary.model.message.bean.MsgFileBean;
import com.wanpinghui.wphlibrary.model.message.bean.PageMsgBean;
import com.wanpinghui.wphlibrary.model.message.bean.RecentMsgBean;
import com.wanpinghui.wphlibrary.model.oauth.UserInfoUtil;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserBean;
import com.yunshl.yunshllibrary.storage.MDBManager;
import com.yunshl.yunshllibrary.utils.TextUtil;
import com.yunshl.yunshllibrary.utils.TimeUtil;

import org.xutils.ex.DbException;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit.Network;
import retrofit.callback.YRequestCallback;
import retrofit.callback.YunShlAction;
import retrofit.callback.YunShlResult;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by xiongning on 17-12-5.
 */

public class MessageServiceImp implements MessageService {

    private String curChatIm=null;

    private int curPage=1;

    private PageMsgBean pageData=null;

    private List<RecentMsgBean> rmsbDatas=null;

    @Override
    public void getMsgList(String chatIM,String group_id,long create_at,final YRequestCallback callback) {
        List<MsgBean> curDatas=null;
        curDatas = MsgDbManager.getInstance().getMsbBeans(chatIM, create_at);
        if(/*curDatas!=null && curDatas.size()>0*/false){
            if(callback!=null){
                callback.onSuccess(curDatas);
            }
        }else {//from server
            Network.getApi(IWPHApi.class).getMsgHistory(group_id,create_at==0?null:create_at,20).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<YunShlResult<GetMsgHistoryResult>>() {
                        @Override
                        public void call(YunShlResult<GetMsgHistoryResult> result) {
                            if (result.isSuccess()) {
                                List<MsgBean> curDatas=result.body.getList();
                                List<MsgBean> processDatas=null;
                                if(curDatas!=null && curDatas.size()>0) {
                                    processDatas=sortMsg(processRcvMsgFromServer(curDatas));
                                }
                                if (callback != null) {
                                    callback.onSuccess(processDatas);
                                }
                            }else {
                                if (callback != null) {
                                    callback.onFailed(result.status, result.msg);
                                }
                            }
                        }
                    }, new YunShlAction<Throwable>(callback));
        }
       /* if(!TextUtil.equals(chatIM,curChatIm)){
            this.curChatIm=chatIM;
            this.curPage=1;
            if(pageData!=null) {
                pageData.getDatas().clear();
                pageData.setHasHistory(false);
            }
        }
        if(pageData==null){
            pageData=new PageMsgBean();
        }
        if(pageData.getDatas()==null) {
            pageData.setDatas(new ArrayList<MsgBean>());
        }
        List<MsgBean> curDatas=null;
        if(pageData.getDatas().size()>0) {
            MsgBean firstMB = pageData.getDatas().get(0);
            curDatas = MsgDbManager.getInstance().getMsbBeans(curChatIm, firstMB);
        }else {
            curDatas = MsgDbManager.getInstance().getMsbBeans(curChatIm, curPage);
        }
        if(curDatas!=null && curDatas.size()>0){
            *//*if(pageData.getDatas()!=null && pageData.getDatas().size()>0)
                curDatas.addAll(pageData.getDatas());
            pageData.setDatas(curDatas);*//*
            pageData.getDatas().addAll(curDatas);
            if(callback!=null){
                callback.onSuccess(curDatas);
            }
        }else {//from server
            long createAt=0;
            if(pageData.getDatas().size()>0) {
                //MsgBean firstMB = pageData.getDatas().get(0);
                MsgBean firstMB = pageData.getDatas().get(pageData.getDatas().size()-1);
                createAt=firstMB.getCreated_at();
            }
            Network.getApi(IWPHApi.class).getMsgHistory(group_id,createAt==0?null:createAt,20).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<YunShlResult<GetMsgHistoryResult>>() {
                        @Override
                        public void call(YunShlResult<GetMsgHistoryResult> result) {
                            if (result.isSuccess()) {
                                if(pageData==null){
                                    pageData=new PageMsgBean();
                                }
                                if(pageData.getDatas()==null) {
                                    pageData.setDatas(new ArrayList<MsgBean>());
                                }
                                List<MsgBean> curDatas=result.body.getList();
                                if(curDatas!=null && curDatas.size()>0) {
                                    List<MsgBean> processDatas=sortMsg(processRcvMsgFromServer(curDatas));
                                   *//* if (pageData.getDatas() != null && pageData.getDatas().size() > 0)
                                        curDatas.addAll(pageData.getDatas());
                                    pageData.setDatas(processDatas);*//*
                                    pageData.getDatas().addAll(curDatas);
                                }
                                if (callback != null) {
                                    callback.onSuccess(curDatas);
                                }
                            }else {
                                if (callback != null) {
                                    callback.onFailed(result.status, result.msg);
                                }
                            }
                        }
                    }, new YunShlAction<Throwable>(callback));
            }*/
    }

    private List<MsgBean> processRcvMsgFromServer(List<MsgBean> curDatas){
        if(curDatas!=null && curDatas.size()>0){
            for(MsgBean mb:curDatas){
                mb.processRcvMsgBean();
            }
            MsgDbManager.getInstance().saveMsbBeanList(curDatas);
        }
        return curDatas;
    }

    @Override
    public PageMsgBean setCatch(List<MsgBean> datas) {
        if(pageData==null){
            pageData=new PageMsgBean();
        }
        if(pageData.getDatas()==null) {
            pageData.setDatas(new ArrayList<MsgBean>());
        }
        boolean isFound=false;
        List<MsgBean> srcDatas=pageData.getDatas();
        if(srcDatas!=null && srcDatas.size()>0){
            for(int i=0;i<srcDatas.size();i++){
                MsgBean mb=srcDatas.get(i);
                for(MsgBean b:datas){
                    if(TextUtil.equals(mb.getId(),b.getId())){
                        isFound=true;
                        mb.setSend_statu(b.getSend_statu());
                        mb.setMsg(b.getMsg());
                        break;
                    }
                }
            }
        }
        if(!isFound){
            List<MsgBean> curDatas=pageData.getDatas();
            if(datas!=null && datas.size()>0)
                datas.addAll(curDatas);
            pageData.setDatas(datas);
        }

        return pageData;
    }

    @Override
    public void uploadFile(String filePath,final YRequestCallback callback) {

        File file = new File(filePath);
        if (!file.exists()) {
            if (callback != null) {
                callback.onFailed(0,"文件不存在，请检查是否开启存储权限");
            }
        }else {
            RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"),file))
                    .build();
            Network.getApi(IWPHApi.class)
                    .uploadIMFile(requestBody)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<YunShlResult<MsgFileBean>>() {
                        @Override
                        public void call(YunShlResult<MsgFileBean> result) {
                            Log.e("Upload","result="+result.msg);
                            if (result.isSuccess()) {
                                if (callback != null) {
                                    callback.onSuccess(result.body);
                                }
                            }
                        }
                    }, new YunShlAction<Throwable>(callback));

        }



    }

    @Override

    public void saveSendMsbBean(MsgBean msgBean,YRequestCallback callback,boolean isSuccess) {
        MsgDbManager.getInstance().saveMsbBean(msgBean);
        if(!isSuccess)
            return;
        Map<String, List<MsgBean>> map = new HashMap<>();
        List<MsgBean> datas=new ArrayList<>();
        datas.add(msgBean);
        map.put("message_list",datas);
        Network.getApi(IWPHApi.class).saveMessages(map).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<YunShlResult<String>>() {
                    @Override
                    public void call(YunShlResult<String> result) {
                        if (result.isSuccess()) {

                        }else {

                        }
                    }
                }, new YunShlAction<Throwable>(callback));
    }

    @Override
    public void getMsgHistory(String groupId, long createAt, final YRequestCallback<List<MsgBean>> callback) {
        Network.getApi(IWPHApi.class)
                .getMsgHistory(groupId,createAt==0?null:createAt,20)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<GetMsgHistoryResult>>() {
                    @Override
                    public void call(YunShlResult<GetMsgHistoryResult> result) {
                        if (result.isSuccess()) {
                            if (callback != null) {
                                callback.onSuccess(result.body.getList());
                            }
                        }else {
                            if (callback != null) {
                                callback.onFailed(result.status, result.msg);
                            }
                        }
                    }
                }, new YunShlAction<Throwable>(callback));
    }

    @Override
    public void getRecentMsgBeanList(final YRequestCallback<List<RecentMsgBean>> callback) {
        Network.getApi(IWPHApi.class)
                .getRecentMsbBeanList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<List<RecentMsgBean>>>() {
                    @Override
                    public void call(YunShlResult<List<RecentMsgBean>> result) {
                        if (result.isSuccess()) {
                            if(rmsbDatas==null)
                                rmsbDatas=new ArrayList<RecentMsgBean>();
                            rmsbDatas.clear();
                            if(result.body!=null && result.body.size()>0){
                                rmsbDatas.addAll(result.body);
                                MsgDbManager.getInstance().updateRecentMsgBeanList(result.body);
                            }else {
                                List<RecentMsgBean> dbDatas=MsgDbManager.getInstance().getRecentMsgBeans();
                                if(dbDatas!=null && dbDatas.size()>0)
                                    rmsbDatas.addAll(dbDatas);
                            }
                            sortRecentMsg();
                            if (callback != null) {
                                callback.onSuccess(rmsbDatas);
                            }
                        }else {
                            if (callback != null) {
                                callback.onFailed(result.status, result.msg);
                            }
                        }
                    }
                }, new YunShlAction<Throwable>(callback));
    }


    private List<MsgBean> sortMsg(List<MsgBean> msgBeens){

        if(msgBeens!=null && msgBeens.size()>0) {
            for(MsgBean mb:msgBeens){
                long create_at=mb.getCreated_at();
                 int len=(create_at+"").length();
                 if(len<13)
                     mb.setCreated_at(create_at*1000);
            }
            Collections.sort(msgBeens, new Comparator<MsgBean>() {
                @Override
                public int compare(MsgBean lhs, MsgBean rhs) {
                    return (int) (rhs.getCreated_at() - lhs.getCreated_at());
                }
            });
        }

        return msgBeens;
    }

    public String getChatTime(long timeSecond){
        //   long time = System.currentTimeMillis() - timeSecond;
        if (TimeUtil.getBetweenDay(System.currentTimeMillis(), timeSecond) >= 1) {
            return TimeUtil.format(timeSecond, "yyyy-MM-dd HH:mm");
        } else {
            return TimeUtil.format(timeSecond, "HH:mm");
        }
    }

    private void sortRecentMsg(){

        if(rmsbDatas!=null && rmsbDatas.size()>0){

            for(RecentMsgBean rmb:rmsbDatas){

                long create_at=rmb.getCreated_at();

                int len=(create_at+"").length();

                if(len<13)

                    rmb.setCreated_at(create_at*1000);

                //Log.e("MessageServiceImp","before:time="+rmb.getCreated_at()+",show="+getChatTime(rmb.getCreated_at()));
            }

        }

        Collections.sort(rmsbDatas, new Comparator<RecentMsgBean>() {
            @Override
            public int compare(RecentMsgBean lhs, RecentMsgBean rhs) {
                Date date1 = new Date(lhs.getCreated_at());
                Date date2 = new Date(rhs.getCreated_at());
                if (date1.before(date2)) {
                    return 1;
                } else  {
                    return -1;
                }
            }
        });
    }


    public List<RecentMsgBean> setRecentMsgBeanCache(List<MsgBean> msgBeans,boolean isChating){

        List<RecentMsgBean> datas=null;

        if(msgBeans!=null && msgBeans.size()>0){
            for(MsgBean msgBean:msgBeans){
                datas=setRecentMsgBeanCache(msgBean,isChating);
            }
        }

        return datas;
    }

    @Override
    public void cleanCacheData() {
        pageData=null;
        rmsbDatas.clear();
        pageData=new PageMsgBean();
    }

    @Override
    public List<RecentMsgBean> getRecentMsgBeanCacheData() {
        return rmsbDatas;
    }

    public List<RecentMsgBean> setRecentMsgBeanCache(MsgBean msgBean, boolean isChating){
        String groupId=msgBean.getGroupId();//msgBean.getFrom_id()+":"+msgBean.getMsg_type()+":"+msgBean.getTo_id();
        RecentMsgBean history=null;
        if(rmsbDatas!=null && rmsbDatas.size()>0){
            for(RecentMsgBean rmb:rmsbDatas){
                if(TextUtil.equals(rmb.getGroup_id(),msgBean.getGroupId())){
                    history=rmb;
                    break;
                }
            }
        }
        RecentMsgBean rmb=new RecentMsgBean();
        rmb.setGroup_id(groupId);
        rmb.setTo_id(msgBean.getTo_id());
        rmb.setFrom_id(msgBean.getFrom_id());
        rmb.setMessage(msgBean.getMessage());
        rmb.setMsg_type(msgBean.getMsg_type());
        rmb.setCreated_at(msgBean.getCreated_at());
        if(history!=null) {
            rmb.setUn_read_count(history.getUn_read_count() + (isChating ? 0 : 1));
            rmsbDatas.remove(history);
        }
        else {
            rmb.setUn_read_count(isChating ? 0 : 1);
        }
        List<RecentMsgBean> addRmsbData=new ArrayList<>();
        addRmsbData.add(rmb);
        if(rmsbDatas!=null && rmsbDatas.size()>0)
            addRmsbData.addAll(rmsbDatas);
        rmsbDatas=addRmsbData;
        sortRecentMsg();
        return rmsbDatas;
    }

    @Override
    public void updateRecentMsgUnRead(RecentMsgBean recentMsgBean) {
        if(rmsbDatas!=null && rmsbDatas.size()>0){
            for(RecentMsgBean rmb:rmsbDatas){
                if(TextUtil.equals(rmb.getGroup_id(),recentMsgBean.getGroup_id())){
                    rmb.setUn_read_count(0);
                    MsgDbManager.getInstance().updateRecentMsgBean(rmb);
                    break;
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("group_id", recentMsgBean.getGroup_id());
        Network.getApi(IWPHApi.class)
                .updateRecentMsbUnReadNum(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<Object>>() {
                    @Override
                    public void call(YunShlResult<Object> result) {
                        if (result.isSuccess()) {
                        }else {

                        }
                    }
                }, new YunShlAction<Throwable>(null));
    }

    @Override
    public void updateRecentMsgUnRead(String group_id) {
        if(rmsbDatas!=null && rmsbDatas.size()>0){
            for(RecentMsgBean rmb:rmsbDatas){
                if(TextUtil.equals(rmb.getGroup_id(),group_id)){
                    rmb.setUn_read_count(0);
                    MsgDbManager.getInstance().updateRecentMsgBean(rmb);
                    break;
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("group_id", group_id);
        Network.getApi(IWPHApi.class)
                .updateRecentMsbUnReadNum(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<Object>>() {
                    @Override
                    public void call(YunShlResult<Object> result) {
                        if (result.isSuccess()) {
                        }else {

                        }
                    }
                }, new YunShlAction<Throwable>(null));
    }
}
